<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\facade\Db;
use think\model\concern\SoftDelete;

class GoodsKillModel extends BaseModel
{
    use SoftDelete;
    protected $table='goods_kill';


    public function getGoodsCoverImgAttribute($key)
    {
        $img_arr = $this['goods_img'];
        return empty($img_arr) ? '': $img_arr[0];
    }

    public function getGoodsImgAttribute($value)
    {
        return empty($value) ? '' : explode(',',$value);
    }

    //商品实际销售价格
    public function getSoldInfoAttr($value,$data)
    {
        $linkSelf = $this->getRelation('linkSelf');
        $info = [];
        if(!empty($linkSelf)){
            foreach ($linkSelf as $vo){
                $sku_info = $vo->getRelation('linkSku');
                if($vo['is_open']==1){
                    $info = [
                        'sku_id' => $sku_info['id'],
                        'sku_name' => $sku_info['name'],
                        'price' => $vo['price'],
                        'stock' => $vo['stock'],
                    ];
                    break;
                }
            }
        }
        return $info;
    }



    /**
     * 获取商品数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @param UserModel|null $user_model 用户模型
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data=[],UserModel $user_model=null)
    {

        $limit = $input_data['limit']??null;

        $where = [];
        $at = $input_data['at']??0; //活动时间
        $where[] = ['at','=',$at];
        if(isset($input_data['id'])){
            $where[]  =['goods_kill_model.id','=',$input_data['id']];
        }

        $cid = $input_data['cid']??0;
        if(!empty($cid)){
            $where[] = ['linkGoods.cid','=',$cid];
        }
        $ct_id = $input_data['ct_id']??0;
        if(!empty($ct_id)){
            $where[] = ['linkGoods.ct_id','=',$ct_id];
        }
        $keyword = $input_data['keyword']??'';
        if(!empty($keyword)){
            $where[] = ['linkGoods.name','like','%'.$keyword.'%'];
        }


        if(app()->http->getName()!='admin' && !isset($input_data['ignore_status'])){
            $where[] = ['linkGoods.status','=',1];
        }

        //处理排序
        $limit_order_field = ['linkGoods.sort','linkGoods.sold_num','linkGoods.views','linkGoods.update_time','linkGoods.price'];
        $order_field = $input_data['order_field']??'';
        $order_field = !in_array($order_field,$limit_order_field)?'linkGoods.sort':$order_field;
        $order_sort = $input_data['order_sort']??'';
        $order_sort = $order_sort=='desc'?'desc':'asc';
        $order = $order_field.' '.$order_sort;

        $model = self::withjoin('linkGoods','left')
            ->with(['linkSelf'=>function($query)use($at){
                $query->with(['linkSku'])->where(['at'=>$at]);
            }])
            ->where($where)->order($order)->group('goods_kill_model.gid')->paginate($limit);


        return $model;
    }

    public static function handleSaveData(array $input_data = [])
    {
//        $input_data['location_index']=empty($input_data['location_index']) || $input_data['location_index']=='false' ?0:1;

        $at = $input_data['at']??0;
        $goods_id = $input_data['gid']??0;

        if(empty($at)) throw new \Exception('请选择活动开始时间');
        if(empty($goods_id)) throw new \Exception('请选择产品');
        //查询产品是否有记录
        $kill_record = [];
        self::where(['at'=>$at,'gid'=>$goods_id])->select()->each(function($item)use(&$kill_record){
            $key = $item['gid'].'_'.$item['sku_id'];
            $kill_record[$key] = $item['id'];
        });

        $price_info = empty($input_data['price_info']) || !is_array($input_data['price_info']) ?[]:$input_data['price_info'];
        $price_insert_all = [];
        foreach($price_info as $vo){
            $sku_id = $vo['sku_id']??0;

            $kill_key = $goods_id.'_'.$sku_id;
            $id = $kill_record[$kill_key]??0; //保留主键
            $price = $vo['price']??0;
            $stock = empty($vo['stock']) || $vo['stock']<0 ? 0 : $vo['stock'];
            $is_open = empty($vo['status_bool'])?0:($vo['status_bool']==='true'?1:0);
            if(empty($price)) throw new \Exception('请输入产品秒杀价格');

            $save_data = [
                'at'=>$at,
                'gid'=>$goods_id,
                'sku_id'=>$sku_id,
                'price'=>$price,
                'stock'=>$stock,
                'is_open'=>$is_open,
            ];

            if($id){
                self::where(['id'=>$id])->update($save_data);
            }else{
                $save_data['create_time'] = time();
                $save_data['update_time'] = time();
                $price_insert_all[]=$save_data;
                self::insert($save_data);
            }
        }
//        count($price_insert_all)>0 && self::insertAll($price_insert_all);
    }

    public static function del(array $input_data = [])
    {
        $goods_id = $input_data['goods_id']??'';
        $at = $input_data['at']??'';
        if(empty($goods_id)) throw new \Exception('参数异常:gid');
        if(empty($at)) throw new \Exception('参数异常:at');
        Db::table('goods_kill')->where(['gid'=>$goods_id,'at'=>$at])->delete();
    }


    //秒杀详情
    public function killInfo()
    {
        return array_merge($this->apiNormalInfo(),[
        ]);
    }


    public function apiFullInfo()
    {

        $linkSelf = $this->getRelation('linkSelf');
        $price_info = [];
        if(!empty($linkSelf)){
            foreach ($linkSelf as $vo){
                $sku_info = $vo->getRelation('linkSku');
                $price_info[] =[
                    'sku_id' => $sku_info['id'],
                    'sku_name' => $sku_info['name'],
                    'price' => $vo['price'],
                    'stock' => $vo['stock'],
                    'is_open' => $vo['is_open'],
                    'status_bool' => $vo['is_open']==1,
                ];
            }
        }
        return array_merge($this->apiNormalInfo(),[
            'update_time'=>$this['update_time'],
            'price_info'=>$price_info,

        ]);
    }

    public function apiNormalInfo()
    {
        $linkGoods = $this->getRelation('linkGoods');
        $sold_info = $this->getAttr('sold_info');
        $og_price = empty($linkGoods)?0 : ($linkGoods['og_price']??0);
        $sold_price = $sold_info['price']??0;
        $p_dis =  empty($og_price) ? 0 : sprintf('%.2f',$sold_price/$og_price*100);
        return array_merge(empty($linkGoods)?[]:$linkGoods->apiNormalInfo(),[
            'id'=>$this['id'],
            'gid'=>$this['gid'],
            'goods_name'=>(string)$linkGoods['name'],
            'goods_cover_img'=>(string)$linkGoods['cover_img'],
            'goods_img'=>$linkGoods['img'],

            'label'=>[
                ['color'=>'bg-red','name'=>'显示抢购']
            ],

            'p_dis'=> empty($p_dis)?'':$p_dis.'折',
            'sold_price'=>empty($sold_price)?'0.00':$sold_price,
            'sku_id'=>$sold_info['sku_id']??0,
            'sku_name'=>$sold_info['sku_name']??'',
        ]);
    }

    public function apiLangNormalInfo($lang)
    {
        $linkGoods = $this->getRelation('linkGoods');
        $sold_info = $this->getAttr('sold_info');
        $og_price = empty($linkGoods)?0 : ($linkGoods['og_price']??0);
        $price = empty($linkGoods)?0 : ($linkGoods['price']??0);
        $sold_price = $sold_info['price']??0;

        $name = (string)$linkGoods['name'];
        $sub_name = (string)$linkGoods['sub_name'];
        if($lang=='ban'){
            $name = (string)$linkGoods['name_ban'];
            $sub_name = (string)$linkGoods['sub_name_ban'];
        }
        return [
            'id' => (int)$this['id'],
            'cover_img' => (string)$linkGoods['cover_img'],
            'name' => $name,
            'sub_name' => (string)$sub_name,
            'price' => (string)$price,          //标价 售价
            'sold_price' => (string)$sold_price,          //售价
        ];
    }



    public function linkSelf()
    {
        return $this->hasMany(self::class,'gid','gid');
    }

    public function linkSku()
    {
        return $this->belongsTo(GoodsSkuPriceModel::class,'sku_id');
    }

    public function linkGoods()
    {
        return $this->belongsTo(GoodsModel::class,'gid');
    }
}